package cu.tedu._05weibo.controller;

import cu.tedu._05weibo.common.response.JsonResult;
import cu.tedu._05weibo.common.response.StatusCode;
import cu.tedu._05weibo.mapper.UserMapper;
import cu.tedu._05weibo.pojo.dto.UserLoginDTO;
import cu.tedu._05weibo.pojo.dto.UserRegDTO;
import cu.tedu._05weibo.pojo.entity.User;
import cu.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO) {

        log.debug("userRegDTO=" + userRegDTO);
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
//        if (userVO != null) {//被占用
//            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
//        }
        //存入数据
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        userMapper.insertUser(user);

        //return new JsonResult(StatusCode.OPERATION_SUCCESS);//注册成功
        return JsonResult.ok();
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {

        System.out.println("userLoginDTO = " + userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) {

            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())) {
            //存储用户唯一标识
            session.setAttribute("user", userVO);
            return new JsonResult(StatusCode.LOGIN_SUCCESS);
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    @ApiOperation(value = "获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
      UserVO userVO=(UserVO) session.getAttribute("user");
      //return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
        return JsonResult.ok(userVO);
    }

    @ApiOperation(value = "退出登录功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");

    }
}
